/**
 * Created by Pasturn on 16/11/12.
 */
var chat = angular.module('chat', ['ui.router']);

var webimutil = new util();
var webimmodel = new model();

chat.config(['$provide', '$stateProvider', '$urlRouterProvider', function($provide, $stateProvider, $urlRouterProvider) {
    "use strict";
    var baseUrl = 'http://ccaiw.picp.net:8888/api/v1.0/' //http://ccaiw.picp.net:8888/api/v1.0
    var appkey = 'p5tvi9dstpyf4'; // 3argexb6re3de e5t4ouvptoo9a
    var userId = 'test3'

    $provide.provider("appconfig", function(){
        this.$get = function () {
            return {
                getBaseUrl: function () {
                    return baseUrl
                },
                getAppKey: function () {
                    return appkey
                },
                getUserId: function () {
                    return userId
                }
            }
        }
    })

    $urlRouterProvider.when("/main", ["$state", "mainDataServer", "mainServer", function($state, mainDataServer, mainServer) {
        var userid = webimutil.CookieHelper.getCookie("loginuserid");
        if (userid) {
            if (!$state.is("main")) {
                $state.go("main")
            }
            return;
        } else {
            $state.go("login");
             mainServer.User.loginout().then(function success () {
                 webimutil.CookieHelper.removeCookie("loginuserid");
                 mainDataServer.loginUser = new webimmodel.UserInfo();
                 $state.go("login");
             });
            return;
        }
    }]).otherwise("/main")

    $stateProvider
        .state('login', {
            url: '/login',
            templateUrl: './assets/tpl/login.htm',
            controller: 'loginController'
        })
        .state('main', {
            url: '/main',
            templateUrl: './assets/tpl/main.htm',
            controller: 'mainController'
        })

}])

chat.service('mainServer', ['$http', '$q', 'appconfig', function ($http, $q, appconfig) {
    "use strict";
    var mainServer = {

    		LoginUser:{},
        User: {
            register: function (username, password) {
                var defer = $q.defer();
                $http({
                    url: appconfig.getBaseUrl() + 'user/register',
                    method: 'GET',
                    params: {
                        username: username,
                        password: password
                    }
                }).success(function (data, header, config, status) {
                    defer.resolve(data)
                }).error(function (data, header, config, status) {
                    defer.reject(data)
                })
                return defer.promise
            },
            // 登录
            login: function (account, password) {
                var defer = $q.defer();
                $http({
                    url: appconfig.getBaseUrl() + 'user/login',
                    method: 'GET',
                    params: {
                        account: account,
                        password: password
                    }
                }).success(function (data, header, config, status) {
                    defer.resolve(data)
                }).error(function (data, header, config, status) {
                    defer.reject(data)
                })
                return defer.promise
            },
            // 注销
            loginout: function (userid) {
                var defer = $q.defer();
                $http({
                    url: appconfig.getBaseUrl() + 'user/' + userid + '/loginout',
                    method: 'GET'
                }).success(function (data, header, config, status) {
                    defer.resolve(data)
                }).error(function (data, header, config, status) {
                    defer.reject(data)
                })
                return defer.promise
            },
            // 设置用户头像
            setPortrait: function (userid, url) {
                var defer = $q.defer();
                $http({
                    url: appconfig.getBaseUrl() + 'user/' + userid + '/set_portrait_uri',
                    method: 'GET'
                }).success(function (data, header, config, status) {
                    defer.resolve(data)
                }).error(function (data, header, config, status) {
                    defer.reject(data)
                })
                return defer.promise
            },
            // 获取Token
            getToken: function (userid) {
                var defer = $q.defer();
                $http({
                    url: appconfig.getBaseUrl() + 'user/' + userid + '/token',
                    method: 'GET'
                }).success(function (data, header, config, status) {
                    defer.resolve(data)
                }).error(function (data, header, config, status) {
                    defer.reject(data)
                })
                return defer.promise
            },
            // 获取用户群组
            getGroups: function (userid) {
                var defer = $q.defer();
                $http({
                    url: appconfig.getBaseUrl() + 'user/' + userid + '/groups',
                    method: 'GET'
                }).success(function (data, header, config, status) {
                    defer.resolve(data)
                }).error(function (data, header, config, status) {
                    defer.reject(data)
                })
                return defer.promise
            },
            // 设置群组置顶
            setTopGroup: function (userid, groupid) {
                var defer = $q.defer();
                $http({
                    url: appconfig.getBaseUrl() + 'user/' + userid + '/setgrouptop',
                    method: 'GET',
                    params: {
                        groupid: groupid,
                        istop: 1
                    }
                }).success(function (data, header, config, status) {
                    defer.resolve(data)
                }).error(function (data, header, config, status) {
                    defer.reject(data)
                })
                return defer.promise
            },
            // 获取用户信息
            getUserInfo: function (userid) {
                var defer = $q.defer();
                $http({
                    url: appconfig.getBaseUrl() + 'user/' + userid,
                    method: 'GET'
                }).success(function (data, header, config, status) {
                    defer.resolve(data)
                }).error(function (data, header, config, status) {
                    defer.reject(data)
                })
                return defer.promise
            },
            // 根据用户名查找用户
            searchUser: function (username) {
                var defer = $q.defer();
                $http({
                    url: appconfig.getBaseUrl() + 'user/find/' + username,
                    method: 'GET'
                }).success(function (data, header, config, status) {
                    defer.resolve(data)
                }).error(function (data, header, config, status) {
                    defer.reject(data)
                })
                return defer.promise
            },
        },
        Group: {
            // 创建群组
            createGroup: function (userids, groupname, groupmemo) {
                var defer = $q.defer();
                $http({
                    url: appconfig.getBaseUrl() + 'group/create',
                    method: 'GET',
                    params: {
                        userids: userids,
                        groupname: groupname,
                        groupmemo: groupmemo,
                    }
                }).success(function (data, header, config, status) {
                    defer.resolve(data)
                }).error(function (data, header, config, status) {
                    defer.reject(data)
                })
                return defer.promise
            },
            // 加入群组
            joinGroup: function (groupid, userids) {
                var defer = $q.defer();
                $http({
                    url: appconfig.getBaseUrl() + 'group/' + groupid + '/join',
                    method: 'GET',
                    params: {
                        userids: userids
                    }
                }).success(function (data, header, config, status) {
                    defer.resolve(data)
                }).error(function (data, header, config, status) {
                    defer.reject(data)
                })
                return defer.promise
            },
            // 退出群组
            quitGroup: function (groupid, userids) {
                var defer = $q.defer();
                $http({
                    url: appconfig.getBaseUrl() + 'group/' + groupid + '/quit',
                    method: 'GET',
                    params: {
                        userids: userids
                    }
                }).success(function (data, header, config, status) {
                    defer.resolve(data)
                }).error(function (data, header, config, status) {
                    defer.reject(data)
                })
                return defer.promise
            },
            // 解散群组
            destroyGroup: function (groupid) {
                var defer = $q.defer();
                $http({
                    url: appconfig.getBaseUrl() + 'group/' + groupid + '/destroy',
                    method: 'GET'
                }).success(function (data, header, config, status) {
                    defer.resolve(data)
                }).error(function (data, header, config, status) {
                    defer.reject(data)
                })
                return defer.promise
            },
            // 设置群管理员
            setGroupAdmin: function (groupid, userid) {
                var defer = $q.defer();
                $http({
                    url: appconfig.getBaseUrl() + 'group/' + groupid + '/setadmin/' + userid,
                    method: 'GET'
                }).success(function (data, header, config, status) {
                    defer.resolve(data)
                }).error(function (data, header, config, status) {
                    defer.reject(data)
                })
                return defer.promise
            },
            // 设置群是否可以加人
            setGroupIsOpen: function () {
                return
            },
            // 设置用户群消息
            setGroupNotify: function (groupid, isnotify) {
                var defer = $q.defer();
                $http({
                    url: appconfig.getBaseUrl() + 'group/' + groupid + '/setnotify',
                    method: 'GET',
                    params: {
                        userid: groupid,
                        isnotify: isnotify
                    }
                }).success(function (data, header, config, status) {
                    defer.resolve(data)
                }).error(function (data, header, config, status) {
                    defer.reject(data)
                })
                return defer.promise
            },
            // 设置群名称和简介
            setGroupInfo: function (groupname, groupmemo) {
                var defer = $q.defer();
                $http({
                    url: appconfig.getBaseUrl() + 'group/' + groupid + '/setgroupinfo',
                    method: 'GET',
                    params: {
                        userid: groupname,
                        isnotify: groupmemo
                    }
                }).success(function (data, header, config, status) {
                    defer.resolve(data)
                }).error(function (data, header, config, status) {
                    defer.reject(data)
                })
                return defer.promise
            },
            // 获取群的用户列表
            getGroupUsers: function (groupid) {
                var defer = $q.defer();
                $http({
                    url: appconfig.getBaseUrl() + 'group/' + groupid + '/users',
                    method: 'GET'
                }).success(function (data, header, config, status) {
                    defer.resolve(data)
                }).error(function (data, header, config, status) {
                    defer.reject(data)
                })
                return defer.promise
            },
            // 获取群的用户详细信息
            getGroupUserInfo: function (groupid) {
                var defer = $q.defer();
                $http({
                    url: appconfig.getBaseUrl() + 'group/' + groupid + '/usersinfo',
                    method: 'GET'
                }).success(function (data, header, config, status) {
                    defer.resolve(data)
                }).error(function (data, header, config, status) {
                    defer.reject(data)
                })
                return defer.promise
            },
            getGroupInfo: function (groupid) {
                var defer = $q.defer();
                $http({
                    url: appconfig.getBaseUrl() + 'group/' + groupid,
                    method: 'GET',
                    params: {
                        groupid: groupid
                    }
                }).success(function (data, header, config, status) {
                    defer.resolve(data)
                }).error(function (data, header, config, status) {
                    defer.reject(data)
                })
                return defer.promise
            },
            // 获取所有群
            getAllGroups: function () {
                var defer = $q.defer();
                $http({
                    url: appconfig.getBaseUrl() + 'group/all',
                    method: 'GET'
                }).success(function (data, header, config, status) {
                    defer.resolve(data)
                }).error(function (data, header, config, status) {
                    defer.reject(data)
                })
                return defer.promise
            },
            // 根据群名字查找群
            searchGroup: function (groupname) {
                var defer = $q.defer();
                $http({
                    url: appconfig.getBaseUrl() + 'group/find/groupname',
                    method: 'GET'
                }).success(function (data, header, config, status) {
                    defer.resolve(data)
                }).error(function (data, header, config, status) {
                    defer.reject(data)
                })
                return defer.promise
            }
        },
        Department: {
            getAllDepartment: function () {
                var defer = $q.defer();
                $http({
                    url: appconfig.getBaseUrl() + 'dep/all',
                    method: 'GET'
                }).success(function(data, header, config, status){
                    defer.resolve(data)
                }).error(function(data, header, config, status){
                    defer.reject(data)
                })
                return defer.promise
            },
            // 获取该组织机构下的员工列表
            getEmployee: function (departmentId) {
                var defer = $q.defer();
                $http({
                    url: appconfig.getBaseUrl() + 'dep/' + departmentId + '/emps',
                    method: 'GET'
                }).success(function(data, header, config, status){
                    defer.resolve(data)
                }).error(function(data, header, config, status){
                    defer.reject(data)
                })
                return defer.promise
            },
            // 获取该组织机构下的组织机构列表
            getDepartmentList: function (departmentId) {
                var defer = $q.defer();
                $http({
                    url: appconfig.getBaseUrl() + 'dep/' + departmentId + '/deps',
                    method: 'GET'
                }).success(function(data, header, config, status){
                    defer.resolve(data)
                }).error(function(data, header, config, status){
                    defer.reject(data)
                })
                return defer.promise
            },
            // 根据departmentName搜索部门
            searchDepartment: function (departmentName) {
                var defer = $q.defer();
                $http({
                    url: appconfig.getBaseUrl() + 'dep/find/' + departmentName,
                    method: 'GET'
                }).success(function (data, header, config, status) {
                    defer.resolve(data)
                }).error(function (data, header, config, status) {
                    defer.reject(data)
                })
                return defer.promise
            }
        }
    }
    return mainServer

}])

chat.factory('conversationServer', ['$q','$rootScope','RongIMSDKServer',
    function($q, $rootScope,RongIMSDKServer){
    "use strict";
    var conversationServer = {};

    conversationServer.atMessagesCache = {};
    conversationServer.historyMessagesCache = {};
    conversationServer.conversationMessageList = [];
    conversationServer.conversationMessageListShow = [];
    conversationServer.pullMessageTime = null;
    conversationServer.remainMessageCount = 5;
    conversationServer.withDrawMessagesCache = {};
    conversationServer.msg_map={};

    function asyncConverGroupNotifition(msgsdk, item) {
        var detail = msgsdk.content
        var comment = "", members = [];
        var isself = (detail.operatorUserId == mainDataServer.loginUser.id);
        switch (detail.operation) {
            case "Add":
                if(isself){
                    comment = '你邀请' +detail.data.data.targetUserDisplayNames.join('、') + "加入了群组";
                }else{
                    comment = detail.data.data.operatorNickname + '邀请' +detail.data.data.targetUserDisplayNames.join('、') + "加入了群组";
                }
                members = detail.data.data.targetUserIds;
                break;
            case "Quit":
                comment = detail.data.data.targetUserDisplayNames.join('、') + "退出了群组"
                members = detail.data.data.targetUserIds;
                break;
            case "Kicked":
                if(isself){
                    comment = '你将' + detail.data.data.targetUserDisplayNames.join('、') + " 移出了群组";
                }else{
                    comment = detail.data.data.operatorNickname + '将' + detail.data.data.targetUserDisplayNames.join('、') + " 移出了群组";
                }
                members = detail.data.data.targetUserIds;
                break;
            case "Rename":
                if(isself){
                    comment = "你修改名称为" + detail.data.data.targetGroupName;
                    // + detail.data.data.targetGroupName;
                }else{
                    comment = detail.data.data.operatorNickname + "修改群名称为" + detail.data.data.targetGroupName;
                }
                break;
            case "Create":
                if(detail.operatorUserId == mainDataServer.loginUser.id){
                    comment = "你创建了群组";
                }else{
                    comment = detail.data.data.operatorNickname + "创建了群组";
                }
                break;
            case "Dismiss":
                comment = detail.data.data.operatorNickname + "解散了群组";
                break;
            default:
                console.log("未知群组通知");
        }

        item.content  = comment;
        // for (var i = 0, len = members.length; i < len; i++) {
        // mainServer.user.getInfo(members[i]).success(function(rep) {
        // if (item.content === comment) {
        // item.content = rep.result.nickname + item.content ;
        // } else {
        // item.content = rep.result.nickname + "、" + item.content ;
        // }
        // })
        // }
    }

    function asyncConverDiscussionNotifition(msgsdk, item) {
        var detail = msgsdk
        var comment = "", members = []
        switch (detail.content.type) {
            case 1:
                comment = " 加入讨论组";
                members = detail.content.extension.split(',');
                break;
            case 2:
                comment = " 退出讨论组"
                members = detail.content.extension.split(',');
                break;
            case 4:
                comment = " 被踢出讨论组";
                members = detail.content.extension.split(',');
                break;
            case 3:
                comment = " 讨论组更名";
                break;
            default:
                console.log("未知讨论组通知");
        }

        item.content  = comment;
        /*
        mainServer.User.getUserInfo(members).then(function (repmem) {
            var lists = repmem.data.result;
            var membersName = [];
            for (var j = 0, len = lists.length; j < len; j++) {
                membersName.push(lists[j].nickname);
            }
            if(membersName){
                item.content = membersName.join('、') + item.content;
            }
        });
        */
    }

    function getHistory(id, type, lastTime, count) {
        var d = $q.defer();
        var conver = type;
        var currentConversationTargetId = id;

        if (!conversationServer.historyMessagesCache[conver + "_" + currentConversationTargetId]) {
            conversationServer.historyMessagesCache[conver + "_" + currentConversationTargetId] = [];
        }

        try {

            RongIMSDKServer.getHistoryMessages(+conver, currentConversationTargetId, lastTime, count).then(function(data) {
                var has = data.has, list = data.data;
                var msglen = list.length;
                if(msglen > 0){
                    conversationServer.pullMessageTime = list[msglen - 1].sentTime;
                }
                var _withDrawMsg = conversationServer.withDrawMessagesCache[conver + "_" + currentConversationTargetId];

                while (msglen--) {
                    var msgsdk = list[msglen];
                    if(_withDrawMsg && _withDrawMsg.indexOf(msgsdk.messageUId) > -1){
                        continue;
                    }

                    switch (msgsdk.messageType) {
                        case webimmodel.MessageType.ContactNotificationMessage:
                            // 历史邀请消息不做处理
                            break;
                        case webimmodel.MessageType.TextMessage:
                        case webimmodel.MessageType.VoiceMessage:
                        case webimmodel.MessageType.LocationMessage:
                        case webimmodel.MessageType.ImageMessage:
                        case webimmodel.MessageType.RichContentMessage:
                        case webimmodel.MessageType.FileMessage:
                            var item = webimmodel.Message.convertMsg(msgsdk);
                            if (item) {
                                unshiftHistoryMessages(currentConversationTargetId, conver, item);
                            }
                            break;
                        case webimmodel.MessageType.GroupNotificationMessage:
                            if (msgsdk.objectName == "RC:GrpNtf") {
                                var item = webimmodel.Message.convertMsg(msgsdk);
                                if (item) {
                                    conversationServer.asyncConverGroupNotifition(msgsdk, item);
                                    unshiftHistoryMessages(currentConversationTargetId, conver, item);
                                }
                            }
                            break;
                        case webimmodel.MessageType.UnknownMessage:
                            if (msgsdk.objectName == "RC:GrpNtf") {
                                var item = webimmodel.Message.convertMsg(msgsdk);
                                if (item) {
                                    conversationServer.asyncConverGroupNotifition(msgsdk, item);
                                    unshiftHistoryMessages(currentConversationTargetId, conver, item);
                                }
                            }
                            break;
                        case webimmodel.MessageType.RecallCommandMessage:
                            if (msgsdk.objectName == "RC:RcCmd") {
                                // var item =
								// webimmodel.Message.convertMsg(msgsdk);
                                // if (item) {
                                // conversationServer.delWithDrawMessage(item.senderUserId,
								// item.conversationType, msgsdk.messageUId);
                                // unshiftHistoryMessages(currentConversationTargetId,
								// conver, item);
                                // }
                                // conversationServer.addWithDrawMessageCache(item.senderUserId,
								// item.conversationType, msgsdk.messageUId);
                            }
                            break;
                        case webimmodel.MessageType.InformationNotificationMessage:
                            var item = webimmodel.Message.convertMsg(msgsdk);
                            if (item) {
                                unshiftHistoryMessages(currentConversationTargetId, conver, item);
                            }
                            break;
                        case webimmodel.MessageType.DiscussionNotificationMessage:
                            if (msgsdk.objectName == "RC:DizNtf") {

                            }
                            break;
                        default:
                            console.log("此消息类型未处理：" + msgsdk.messageType);
                            break;
                    }

                }
                var addtime = conversationServer.historyMessagesCache[conver + "_" + currentConversationTargetId][0];
                if (addtime && addtime.panelType != webimmodel.PanelType.Time) {
                    unshiftHistoryMessages(currentConversationTargetId, conver, new webimmodel.TimePanl(conversationServer.historyMessagesCache[conver + "_" + currentConversationTargetId][0].sentTime));
                }
                // 遍历缓存,过滤撤回消息
                // var _withDrawMsg =
				// conversationServer.withDrawMessagesCache[conver + "_" +
				// currentConversationTargetId];
                // if(_withDrawMsg){
                // for(var i = 0;i < _withDrawMsg.length;i++){
                // delWithDrawMessage(currentConversationTargetId, conver,
				// _withDrawMsg[i]);
                // }
                // }

                d.resolve(has);
            }, function(err) {
                d.reject(err);
                console.log('获取历史消息失败');
            });
        } catch (err) {
            console.log("SDK error" + err);
        }

        return d.promise;
    }

    function unshiftHistoryMessages(id, type, item) {
        var arr = conversationServer.historyMessagesCache[type + "_" + id] || [];
        if (arr[0] && item.messageUId && item.messageUId === arr[0].messageUId) {
            return;
        }

        if (arr[0] && arr[0].sentTime && arr[0].panelType != webimmodel.PanelType.Time && item.sentTime) {
            if (compareDateIsAddSpan(arr[0].sentTime, item.sentTime)) {
                arr.unshift(new webimmodel.TimePanl(arr[0].sentTime));
            }
        }
        messageAddUserInfo(item);
        arr.unshift(item);
    }

    // 定时清理消息缓存
    function clearHistoryMessages(id, type) {
        var currenthis = conversationServer.historyMessagesCache[type + "_" + id];
        var counter = 0,counterAll = 0;
        for(var i = currenthis.length - 1; i > -1; i--){
            if (currenthis[i].panelType == webimmodel.PanelType.Message) {
                counter++;
            }
            if (counter >= conversationServer.remainMessageCount && currenthis[i].panelType == webimmodel.PanelType.Time) {
                currenthis.splice(0, i);
                conversationServer.unshiftHistoryMessages(id, type, new webimmodel.GetMoreMessagePanel());
                break;
            }
        }
    }

    function getLastMessageTime(id, type){
        var currenthis = conversationServer.historyMessagesCache[type + "_" + id];
        var sentTime = 0;
        for (var i = 0; i < currenthis.length; i++) {
            if (currenthis[i].panelType == webimmodel.PanelType.Message) {
                sentTime = (new Date(currenthis[i].sentTime)).getTime();
                break;
            }
        }
        return sentTime;
    }

    function delWithDrawMessage(id, type, uid){
        var currenthis = conversationServer.historyMessagesCache[type + "_" + id];
        if(currenthis){
            for (var i = 0; i < currenthis.length; i++) {
                if (currenthis[i].panelType == webimmodel.PanelType.Message && currenthis[i].messageUId == uid) {
                    if(i > 0 && i < currenthis.length - 1 && currenthis[i - 1].panelType == webimmodel.PanelType.Time && currenthis[i + 1].panelType == webimmodel.PanelType.Time
                        || i == currenthis.length - 1 && currenthis[i - 1].panelType == webimmodel.PanelType.Time
                    ){
                        currenthis.splice(i-1, 2);
                    }
                    else{
                        currenthis.splice(i, 1);
                    }
                    break;
                }
            }
        }

        currenthis = conversationServer.conversationMessageList;
        if(currenthis){
            for (var i = 0; i < currenthis.length; i++) {
                if (currenthis[i].panelType == webimmodel.PanelType.Message && currenthis[i].messageUId == uid) {
                    if(i > 0 && i < currenthis.length - 1 && currenthis[i - 1].panelType == webimmodel.PanelType.Time && currenthis[i + 1].panelType == webimmodel.PanelType.Time
                        || i == currenthis.length - 1 && currenthis[i - 1].panelType == webimmodel.PanelType.Time
                    ){
                        currenthis.splice(i-1, 2);
                    }
                    else{
                        currenthis.splice(i, 1);
                    }
                    break;
                }
            }
        }

        currenthis = conversationServer.conversationMessageListShow;
        if(currenthis){
            for (var i = 0; i < currenthis.length; i++) {
                if (currenthis[i].panelType == webimmodel.PanelType.Message && currenthis[i].messageUId == uid) {
                    if(i > 0 && i < currenthis.length - 1 && currenthis[i - 1].panelType == webimmodel.PanelType.Time && currenthis[i + 1].panelType == webimmodel.PanelType.Time
                        || i == currenthis.length - 1 && currenthis[i - 1].panelType == webimmodel.PanelType.Time
                    ){
                        currenthis.splice(i-1, 2);
                    }
                    else{
                        currenthis.splice(i, 1);
                    }
                    break;
                }
            }
        }

    }

    function compareDateIsAddSpan(first, second) {
        if (Object.prototype.toString.call(first) == "[object Date]" && Object.prototype.toString.call(second) == "[object Date]") {
            var pre = first.toString();
            var cur = second.toString();
            return pre.substring(0, pre.lastIndexOf(":")) != cur.substring(0, cur.lastIndexOf(":"))
        } else {
            return false;
        }
    }

    function addHistoryMessages(id, type, item) {
        var arr = conversationServer.historyMessagesCache[type + "_" + id] || [];
        var exist = false;
        // if(item.senderUserId != mainDataServer.loginUser.id){
        exist = checkMessageExist(id, type, item.messageUId);
        if (exist) {
            console.log('exist离线消息有重复');
            return;
        }
        // }

        if (arr[arr.length - 1] && arr[arr.length - 1].panelType != webimmodel.PanelType.Time && arr[arr.length - 1].sentTime && item.sentTime) {
            if (compareDateIsAddSpan(arr[arr.length - 1].sentTime, item.sentTime)) {
                arr.push(new webimmodel.TimePanl(item.sentTime));
                // 判断如果是当前会话的消息则加入
                if (type == mainDataServer.conversation.currentConversation.targetType && id == mainDataServer.conversation.currentConversation.targetId) {
                    conversationServer.conversationMessageListShow.push(new webimmodel.TimePanl(item.sentTime));
                }
            }
        }

        //console.info(item.targetId)
        $rootScope.$broadcast("msg_in",item);

        // messageAddUserInfo(item);
        arr.push(item);
        // 判断如果是当前会话的消息则加入
        // if (type ==
		// mainDataServer.conversation.currentConversation.targetType && id ==
		// mainDataServer.conversation.currentConversation.targetId) {
           // conversationServer.conversationMessageListShow.push(item);
        // }
    }

    function addAtMessage(id, type, item){
        if (!conversationServer.atMessagesCache[type + "_" + id]) {
            conversationServer.atMessagesCache[type + "_" + id] = [];
        }
        var atMsg = { "messageUId": item.messageUId, "mentionedInfo": item.mentionedInfo };
        conversationServer.atMessagesCache[type + "_" + id].push(atMsg);
    }

    function addWithDrawMessageCache(id, type, msgUid){
        if (!conversationServer.withDrawMessagesCache[type + "_" + id]) {
            conversationServer.withDrawMessagesCache[type + "_" + id] = [];
        }
        conversationServer.withDrawMessagesCache[type + "_" + id].push(msgUid);
    }

    // 消息里没有用户信息，要去本地的好友列表里查找
    function messageAddUserInfo(item) {
        if (!item.senderUserId) {
            return item;
        }

        var user;
        if (item.messageDirection == 1) {
            item.senderUserName = mainDataServer.loginUser.nickName;
            item.imgSrc = mainDataServer.loginUser.portraitUri;
            item.senderUserImgSrc = mainDataServer.loginUser.firstchar;
        } else {
            switch (item.conversationType) {
                case webimmodel.conversationType.Private:
                    user = mainDataServer.contactsList.getFriendById(item.senderUserId);
                    if(!user){
                        user = mainDataServer.contactsList.getNonFriendById(item.senderUserId);
                    }
                    break;
                case webimmodel.conversationType.Group:
                    user = mainDataServer.contactsList.getGroupMember(item.targetId, item.senderUserId);
                    break;
                case webimmodel.conversationType.Discussion:

                    break;
                case webimmodel.conversationType.System:

                    break;
                default:
                    console.log("暂不支持此会话类型");
            }
            if (user) {
                item.senderUserName = user.displayName || user.name;
                item.senderUserImgSrc = user.firstchar;
                item.imgSrc = user.imgSrc
            }
        }
        return item;
    }

    function updateHistoryMessagesCache(id, type, name, portrait){
        var currenthis = conversationServer.historyMessagesCache[type + "_" + id];
        angular.forEach(currenthis, function(value, key){
            if (value.panelType == webimmodel.PanelType.Message && value.senderUserId == id){
                value.senderUserName = name;
                value.imgSrc = portrait;

            }
        });
    }
    function checkMessageExist(id, type, messageuid){
        var currenthis = conversationServer.historyMessagesCache[type + "_" + id];
        var keepGoing = true;
        if(!messageuid){
            return false;
        }
        angular.forEach(currenthis, function (value, key) {
            if(keepGoing){
                if (value.panelType == webimmodel.PanelType.Message && value.messageUId == messageuid) {
                    keepGoing = false;
                }
            }
        });
        return !keepGoing;
    }

    function updateSendMessage(id, type, msg){
        var currenthis = conversationServer.historyMessagesCache[type + "_" + id];
        for(var i = currenthis.length - 1; i > -1; i--){
            if (currenthis[i].panelType == webimmodel.PanelType.Message
                && currenthis[i].messageUId == undefined
                && currenthis[i].messageDirection == webimmodel.MessageDirection.SEND
                && currenthis[i].messageId == msg.messageId
            ) {
                currenthis[i].messageUId = msg.messageUId;
                currenthis[i].sentStatus = webimmodel.SentStatus.SENT;
                currenthis.splice(i, 1, msg);
                break;
            }
        }
    }

    function getMessageById(id, type, messageuid){
        var currenthis = conversationServer.historyMessagesCache[type + "_" + id];
        var keepGoing = true;
        var msg = null;
        angular.forEach(currenthis, function (value, key) {
            if(keepGoing){
                if (value.panelType == webimmodel.PanelType.Message && value.messageUId == messageuid) {
                    keepGoing = false;
                    msg = value;
                }
            }
        });
        return msg;
    }

    function sendReadReceiptMessage(id, type, messageuid, sendtime){
        var messageUId = messageuid;
        var lastMessageSendTime = sendtime;
        // if(targetType != webimmodel.conversationType.Private && targetType !=
		// webimmodel.conversationType.Group){
        if(type != webimmodel.conversationType.Private){
            return;
        }
        var msg = RongIMLib.ReadReceiptMessage.obtain(messageUId, lastMessageSendTime, 1);
        RongIMSDKServer.sendMessage(type, id, msg).then(function() {

        }, function(error) {
            console.log('sendReadReceiptMessage error', error.errorCode);
        });
    }

    function sendSyncReadStatusMessage(id, type, sendtime){
        var lastMessageSendTime = sendtime;
        if(type != webimmodel.conversationType.Group){
            return;
        }
        var msg = new RongIMLib.SyncReadStatusMessage({lastMessageSendTime: sendtime});
        RongIMSDKServer.sendMessage(type, id, msg).then(function() {

        }, function(error) {
            console.log('sendSyncReadStatusMessage error', error.errorCode);
        });
    }

    function pushMsg(data){
    	if(!conversationServer.msg_map["u_"+data.targetId]){
    		conversationServer.msg_map["u_"+data.targetId]=[];
    	}
    		conversationServer.msg_map["u_"+data.targetId].push(data);

    }

    conversationServer.getHistory = getHistory;
    conversationServer.addHistoryMessages = addHistoryMessages;
    conversationServer.messageAddUserInfo = messageAddUserInfo;
    conversationServer.unshiftHistoryMessages = unshiftHistoryMessages;
    conversationServer.asyncConverGroupNotifition = asyncConverGroupNotifition;
    conversationServer.asyncConverDiscussionNotifition = asyncConverDiscussionNotifition;
    conversationServer.updateHistoryMessagesCache = updateHistoryMessagesCache;
    conversationServer.checkMessageExist = checkMessageExist;
    conversationServer.addAtMessage = addAtMessage;
    conversationServer.clearHistoryMessages = clearHistoryMessages;
    conversationServer.getLastMessageTime = getLastMessageTime;
    conversationServer.getMessageById = getMessageById;
    conversationServer.updateSendMessage = updateSendMessage;
    conversationServer.delWithDrawMessage = delWithDrawMessage;
    conversationServer.addWithDrawMessageCache = addWithDrawMessageCache;
    conversationServer.sendReadReceiptMessage = sendReadReceiptMessage;
    conversationServer.sendSyncReadStatusMessage = sendSyncReadStatusMessage;
    conversationServer.pushMsg = pushMsg;
    return conversationServer
}])


chat.service('RongIMSDKServer', ['$q', function ($q) {
    "use strict";
    var service = {
        init: function (appkey) {
            RongIMLib.RongIMClient.init(appkey)
        },
        connect: function (token) {
            var defer = $q.defer()
            RongIMLib.RongIMClient.connect(token, {
                onSuccess: function (data) {
                    defer.resolve(data)
                },
                onTokenIncorrect: function () {
                    defer.reject({ tokenError: true })
                },
                onError: function(errorCode) {
                    defer.reject({ errorCode: errorCode});
                    var info = '';
                    switch (errorCode) {
                        case RongIMLib.ErrorCode.TIMEOUT:
                            info = '连接超时';
                            break;
                        case RongIMLib.ErrorCode.UNKNOWN:
                            info = '未知错误';
                            break;
                        case RongIMLib.ConnectionState.UNACCEPTABLE_PROTOCOL_VERSION:
                            info = '不可接受的协议版本';
                            break;
                        case RongIMLib.ConnectionState.IDENTIFIER_REJECTED:
                            info = 'appkey不正确';
                            break;
                        case RongIMLib.ConnectionState.SERVER_UNAVAILABLE:
                            info = '服务器不可用';
                            break;
                        case RongIMLib.ConnectionState.NOT_AUTHORIZED:
                            info = '未认证';
                            break;
                        case RongIMLib.ConnectionState.REDIRECT:
                            info = '重新获取导航';
                            break;
                        case RongIMLib.ConnectionState.APP_BLOCK_OR_DELETE:
                            info = '应用已被封禁或已被删除';
                            break;
                        case RongIMLib.ConnectionState.BLOCK:
                            info = '用户被封禁';
                            break;
                    }
                    console.log("失败:" + info + errorCode);
                }
            })
            return defer.promise
        },
        setConnectionStatusListener: function () {
            return RongIMClient.setConnectionStatusListener({
                onChanged: function (status) {
                    switch (status) {
                        // 链接成功
                        case RongIMLib.ConnectionStatus.CONNECTED:
                            console.log('链接成功');
                            break;
                        // 正在链接
                        case RongIMLib.ConnectionStatus.CONNECTING:
                            console.log('正在链接');
                            break;
                        // 重新链接
                        case RongIMLib.ConnectionStatus.DISCONNECTED:
                            console.log('断开连接');
                            break;
                        // 其他设备登录
                        case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
                            console.log('其他设备登录');
                            break;
                        // 网络不可用
                        case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
                            console.log('网络不可用');
                            break;
                    }
                }
            })
        },
        setOnReceiveMessageListener: function (option) {
            RongIMClient.setOnReceiveMessageListener(option)
        },
        addMessageAndOperation: function (msg) {
            var key = meg.conversationType + '_' + msg.targetId

        },
        startCustomService: function (tagetId) {
            var defer = $q.defer();
            RongIMLib.RongIMClient.getInstance().startCustomService(tagetId, {
                onSuccess: function () {
                    defer.resolve()
                },
                onError: function () {
                    defer.reject()
                }
            })
            return defer.promise
        },
        sendReadReceiptMessage: function (targetId, type) {
            var that = this
            RongIMLib.RongIMClient.getInstance()
                .getConversation(Number(type), targetId, {
                    onSuccess: function (data) {
                        if (data) {
                            var read = RongIMLib.ReadReceiptMessage
                                .obtain(data.latestMessage.messageUId,
                                data.latestMessage.sentTime, "1");

                            that.sendMessage(type, targetId, read);
                        }
                    },
                    onError: function () {}
                })
        },
        sendMessage: function(conver, targetId, content) {
            var defer = $q.defer()
            RongIMLib.RongIMClient.getInstance().sendMessage(conver, targetId+"", content, {
                onSuccess: function (data) {
                    defer.resolve(data);
                },
                onError: function (errorCode, message) {
                    defer.reject({errorCode: errorCode, message: message});
                    var info = '';
                    switch (errorCode) {
                        case RongIMLib.ErrorCode.TIMEOUT:
                            info = '超时';
                            break;
                        case RongIMLib.ErrorCode.UNKNOWN:
                            info = '未知错误';
                            break;
                        case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
                            info = '在黑名单中，无法向对方发送消息';
                            break;
                        case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
                            info = '不在讨论组中';
                            break;
                        case RongIMLib.ErrorCode.NOT_IN_GROUP:
                            info = '不在群组中';
                            break;
                        case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
                            info = '不在聊天室中';
                            break;
                        default:
                            info = "";
                            break;
                    }
                    console.log('发送失败:' + info);
                }
            })
            return defer.promise
        },

        reconnect: function (callback) {
            RongIMLib.RongIMClient.reconnect(callback)
        },

        disconnect: function () {
            RongIMLib.RongIMClient.disconnect()
        },

        logout: function () {
            if (RongIMLib && RongIMLib.RongIMClient) {
                RongIMLib.RongIMClient.getInstance().logout()
            }
        },

        clearUnreadCount: function (type, targetId) {
            var defer = $q.defer();
            RongIMLib.RongIMClient.getInstance()
                .clearUnreadCount(type, targetId, {
                    onSuceess: function (data) {
                        defer.resolve(data);
                    },
                    onError: function (error) {
                        defer.reject(error)
                    }
                })
            return defer.promise
        },

        getTotalUnreadCount: function () {
            var defer = $q.defer()
            RongIMLib.RongIMClient.getInstance()
                .getTotalUnreadCount({
                    onSuccess: function(num) {
                        defer.resolve(num);
                    },
                    onError: function() {
                        defer.reject();
                    }
                });
            return defer.promise;
        },

        getConversationList: function () {
            var defer = $q.defer();
            RongIMLib.RongIMClient.getInstance()
                .getConversationList({
                    onSuccess: function(data) {
                        defer.resolve(data);
                    },
                    onError: function(error) {
                        defer.reject(error);
                    }
                }, null);
            return defer.promise;
        },

        getConversation: function (type, targetId) {

           /*
			 * var defer = $q.defer(); console.info(type)
			 * console.info(targetId);
			 * RongIMLib.RongIMClient.getInstance().getConversation(parseInt(type),
			 * targetId.userid, { onSuccess: function(data) {
			 * defer.resolve(data); }, onError: function(error) {
			 * defer.reject(error); } }) return defer.promise
			 */
        },

        updateConversation: function (con) {
            RongIMLib.RongIMClient.getInstance().updateConversation(con);
        },

        removeConversation: function (type, targetId) {
            var defer = $q.defer()
            RongIMLib.RongIMClient.getInstance()
                .removeConversation(type, targetId, {
                    onSuccess: function (data) {
                        defer.resolve(data)
                    },
                    onError: function (error) {
                        defer.reject(error)
                    }
                })
            return defer.promise
        },

        getHistoryMessages: function (type, targetId) {
            var defer = $q.defer()
            RongIMLib.RongIMClient.getInstance()
                .getHistoryMessages(type, targetId, {
                    onSuccess: function(data, has) {
                        defer.resolve({
                            data: data,
                            has: has
                        })
                    },
                    onError: function (error) {
                        defer.reject(error)
                    }
                })
            return defer.promise
        },

        getDraft: function (type, targetId) {
            return RongIMLib.RongIMClient.getInstance()
                .getTextMessageDraft(type, targetId)
        },

        setDraft: function (type, targetId) {
            return RongIMLib.RongIMClient.getInstance()
                .saveTextMessageDraft(type, targetId)
        },

        clearDraft: function (type, targetId) {
            return RongIMLib.RongIMClient.getInstance()
                .clearTextMessageDraft(type, targetId)
        }
    };
    return service
}]);

chat.factory("mainDataServer", ["$q", "RongIMSDKServer", "mainServer", function ($q, RongIMSDKServer, mainServer) {
    var mainDataServer = {};
        mainDataServer.loginUser = {};
        mainDataServer.isConnected = false;
        mainDataServer.isTyping = false;
        mainDataServer.conversation = {
            totalUnreadCount: 0,
            lastOfflineMsg: null,
            conversations: [],
            currentConversation: {},
            parseConversation: function () {
                "use strict";

            },
            updateConversation: function () {
                "use strict";

            },
            createConversation: function (targetType, targetId) {
                "use strict";
                var item
                item.targetId = targetId;
                item.targetType = targetType;
                switch (targetType) {
                    case webimmodel.conversationType.Private:
                        var friendinfo = mainServer.User.getUserInfo(targetId)
                        if (friendinfo) {
                            item.title = friendinfo.displayName || friendinfo.name;
                            item.firstchar = friendinfo.firstchar;
                            item.imgSrc = friendinfo.imgSrc;
                        }
                        break;
                    case webimmodel.conversationType.Group:
                        var groupinfo = mainServer.Group.getGroupInfo(targetId);
                        if (groupinfo) {
                            item.title = groupinfo.name;
                            item.firstchar = groupinfo.firstchar;
                        }
                        break;
                    default:
                        console.log("暂不支持创建此类型会话");
                }
                return item;
            },
            getConversation: function(type, id) {
                for (var i = 0, len = mainDataServer.conversation.conversations.length; i < len; i++) {
                    if (mainDataServer.conversation.conversations[i].targetType == type && mainDataServer.conversation.conversations[i].targetId == id) {
                        return mainDataServer.conversation.conversations[i];
                    }
                }
                return null;
            },
            updateConversationTitle: function(type, id, title) {
                for (var i = 0, len = mainDataServer.conversation.conversations.length; i < len; i++) {
                    if (mainDataServer.conversation.conversations[i].targetType == type && mainDataServer.conversation.conversations[i].targetId == id) {
                        mainDataServer.conversation.conversations[i].title = title;
                        return true;
                    }
                }
                return false;
            },
            updateConversationDetail: function(type, id, title, portrait) {
                for (var i = 0, len = mainDataServer.conversation.conversations.length; i < len; i++) {
                    if (mainDataServer.conversation.conversations[i].targetType == type && mainDataServer.conversation.conversations[i].targetId == id) {
                        mainDataServer.conversation.conversations[i].title = title;
                        mainDataServer.conversation.conversations[i].imgSrc = portrait;
                        return true;
                    }
                }
                return false;
            },
            updateConStatic: function (msg, add, isChat) {
                var type = msg.conversationType , id = msg.targetId;
                var hasCon = false;
                if (type == webimmodel.conversationType.Discussion || type == webimmodel.conversationType.System && msg.messageType != webimmodel.MessageType.ContactNotificationMessage || type == webimmodel.conversationType.ChartRoom) {
                    return;
                }
                if(msg.messageType == webimmodel.MessageType.ReadReceiptMessage
                    || msg.messageType == webimmodel.MessageType.TypingStatusMessage
                    || msg.messageType == webimmodel.MessageType.SyncReadStatusMessage
                    || msg.messageType == webimmodel.MessageType.ReadReceiptRequestMessage
                    || msg.messageType == webimmodel.MessageType.ReadReceiptResponseMessage
                ){
                    return ;
                }

                RongIMSDKServer.getConversation(type, id).then(function (data) {
                    if (data) {
                        var result = mainDataServer.conversation.parseConversation(data);
                        var oldUnread = 0, totalUnreadCount = mainDataServer.conversation.totalUnreadCount, isfirst = false, conversationItem;
                        for (var i = 0, len = mainDataServer.conversation.conversations.length; i < len; i++) {
                            conversationItem = mainDataServer.conversation.conversations[i];
                            if (conversationItem.targetType == type && conversationItem.targetId == id) {
                                oldUnread = conversationItem.unReadNum;
                                if(i == 0){
                                    isfirst = true;
                                    conversationItem.lastMsg = result.item.lastMsg;
                                    conversationItem.unReadNum = result.item.unReadNum;
                                    conversationItem.lastTime = result.item.lastTime;
                                    if (msg.senderUserId == mainDataServer.loginUser.id) {
                                        RongIMSDKServer.clearUnreadCount(mainDataServer.conversation.currentConversation.targetType, mainDataServer.conversation.currentConversation.targetId);
                                        totalUnreadCount = totalUnreadCount - oldUnread;
                                        result.item.unReadNum = 0;
                                        conversationItem.atStr = '';
                                    }
                                    else{
                                        conversationItem.atStr = result.item.atStr;
                                    }
                                }
                                else{
                                    mainDataServer.conversation.conversations.splice(i, 1);
                                }
                                break;
                            }
                        }
                        if(isChat && type == mainDataServer.conversation.currentConversation.targetType && id == mainDataServer.conversation.currentConversation.targetId){
                            RongIMSDKServer.clearUnreadCount(mainDataServer.conversation.currentConversation.targetType, mainDataServer.conversation.currentConversation.targetId);
                            totalUnreadCount = totalUnreadCount - oldUnread;
                            result.item.unReadNum = 0;
                            result.item.atStr = '';
                        }else{
                            if(msg.senderUserId == mainDataServer.loginUser.id){
                                RongIMSDKServer.clearUnreadCount(mainDataServer.conversation.currentConversation.targetType, mainDataServer.conversation.currentConversation.targetId);
                                totalUnreadCount = totalUnreadCount - oldUnread;
                                result.item.unReadNum = 0;
                                result.item.atStr = '';
                            }
                            else{
                                totalUnreadCount = totalUnreadCount - oldUnread + result.item.unReadNum;
                            }
                        }
                        mainDataServer.conversation.totalUnreadCount = totalUnreadCount;
                        if(add && !isfirst){
                            mainDataServer.conversation.conversations.unshift(result.item);
                        }
                    }
                    else {
                        console.log('无法获取该会话', type, id);
                    }
                }, function (err) {
                    console.log("RongIMSDKServer.getConversation err:" + err, type, id);
                });
            },
            setDraft: function(type, id, msg) {
                for (var i = 0, len = mainDataServer.conversation.conversations.length; i < len; i++) {
                    if (mainDataServer.conversation.conversations[i].targetType == type && mainDataServer.conversation.conversations[i].targetId == id) {
                        mainDataServer.conversation.conversations[i].draftMsg = msg;
                        return true;
                    }
                }
                return false;
            },
            clearMessagesUnreadStatus: function(type, targetid) {
                for (var i = 0, len = mainDataServer.conversation.conversations.length; i < len; i++) {
                    if (mainDataServer.conversation.conversations[i].targetType == type && mainDataServer.conversation.conversations[i].targetId == targetid) {
                        mainDataServer.conversation.conversations[i].unReadNum = 0;
                        return true;
                    }
                }
                return false;
            }
        }
    return mainDataServer
}])


chat.run(['$http', 'mainServer', '$rootScope', 'appconfig',
    function ($http,  mainServer, $rootScope, appconfig) {
    "use strict";

        $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
            console.log(event, toState, toParams, fromState, fromParams)
            if (toState.name!="login" ) {
                // event.preventDefault();
                // $state.transitionTo("login");
            }
        });

    }
])



/*
 *   控制器
 *
 *
 *
 */

chat.controller('loginController', ['$scope','$rootScope', '$state', 'mainServer', function ($scope, $rootScope, $state, mainServer) {
    "use strict";
    $scope.login = function (account, password) {
        mainServer.User.login(account, password)
            .then(function success (data) {
                window.LoginUser= data.result;
                $rootScope.userid = data.result.userid
                webimutil.CookieHelper.setCookie("loginuserid", data.result.userid, 3);
                $state.go('main')
            })
            .catch(function error (data) {
                console.log(data)
            })
    }
}])

chat.controller('mainController', ['$scope', '$http','$state', 'mainServer','$rootScope', 'RongIMSDKServer','conversationServer', 'appconfig',
    function($scope, $http,$state, mainServer,$rootScope, RongIMSDKServer, conversationServer, appconfig){
    "use strict";

        var userId =  webimutil.CookieHelper.getCookie("loginuserid");

        if(userId){
            $rootScope.userId = userId;

            mainServer.User.getUserInfo (userId).then(function success (data) {
                    window.LoginUser = data.result
                    $scope.userInfo = data.result
                })
                .catch(function error (err) {
                    console.log(err)
                })
        }

        $scope.logout = function () {
            if(userId) {
                mainServer.User.loginout(userId).then(function success(data) {
                    $state.go('login')
                    webimutil.CookieHelper.removeCookie("loginuserid");
                }).catch(function error(error) {
                    console.log(error)
                })
            }
        };

        if(userId) {
            mainServer.User.getToken(userId)
                .then(function success (data) {
                    var token = data.result.token
                    RongIMSDKServer.init(appconfig.getAppKey())
                    RongIMSDKServer.connect(token)
                    RongIMSDKServer.setConnectionStatusListener()
                    RongIMSDKServer.setOnReceiveMessageListener({
                        onReceived: function (message) {
                            switch(message.messageType){
                                case RongIMClient.MessageType.TextMessage:
                                case RongIMClient.MessageType.LocationMessage:
                                case RongIMClient.MessageType.RichContentMessage:
                                case RongIMClient.MessageType.ImageMessage:
                                    addMessage(message)
                                    break;

                                case RongIMClient.MessageType.VoiceMessage:
                                    // 对声音进行预加载
                                    // message.content.content 格式为 AMR
                                    // 格式的 base64 码
                                    RongIMLib.RongIMVoice.preLoaded(message.content.content);
                                    break;

                                case RongIMClient.MessageType.DiscussionNotificationMessage:
                                    // do something...
                                    break;

                                case RongIMClient.MessageType.InformationNotificationMessage:
                                    // do something...
                                    break;
                                case RongIMClient.MessageType.ContactNotificationMessage:
                                    // do something...
                                    break;
                                case RongIMClient.MessageType.ProfileNotificationMessage:
                                    // do something...
                                    break;
                                case RongIMClient.MessageType.CommandNotificationMessage:
                                    // do something...
                                    break;
                                case RongIMClient.MessageType.CommandMessage:
                                    // do something...
                                    break;
                                case RongIMClient.MessageType.UnknownMessage:
                                    // do something...
                                    break;
                                default:
                                    break;
                                // 自定义消息
                                // do something...
                            }
                        }}
                    )
                })
                .catch(function error (data) {
                    console.log(data)
                })
            }

        function addMessage(msg){
            conversationServer.addHistoryMessages(msg.targetId, msg.conversationType, msg);
        }
    //获取当前用户部门
    mainServer.Department.getAllDepartment()
        .then(function success (data) {
            $scope.$broadcast('contactlist', data.result)
        })
        .catch(function error (error) {
            console.log(error)
        });
   //获取当前用户群组
    mainServer.User.getGroups(userId)
        .then(function success (data) {
            $scope.$broadcast('grouplist', data.result)
        })
        .catch(function error (error){
            console.log(error)
        })

    $scope.$on('contact', function(e, d) {
    	var data={};
    	data.targetId=d;
    	data.type='user';
        $scope.$broadcast('conversation', data)
    })

    $scope.$on('group', function(e, d) {
    	var data={};
    	data.targetId=d;
    	data.type='group';
        $scope.$broadcast('conversation', data)
    });

    $scope.$on('_grouplist', function(e, d) {
        $scope.$broadcast('grouplist', d)
    })

}])

/*
 *
 *   通讯录控制器
 *
 */

chat.controller('contactController', ['$scope', 'mainServer','$rootScope',
    function($scope, mainServer, $rootScope){
    "use strict";

    var contactGroup = {}

    $scope.$on('contactlist', function(e, data) {
        $scope.contactlist = data
        angular.forEach($scope.contactlist, function (comp, ckey) {
            angular.forEach(comp.deps, function (dep, dkey) {
              contactGroup[ckey + '_' + dkey] = false
            })
        })
        $scope.contactGroup = contactGroup
    });

    $scope.$on('grouplist', function(e, data) {
        $scope.grouplist = data
    })

    $scope.onPanel = 'contact'

    $scope.selectPanel = function (panel) {
        $scope.onPanel = panel
    }

    $scope.getAllMembers = function () {
        $scope.allMembers = []

        mainServer.Department.getAllDepartment().then(function success (data) {
            var allcom = data.result,
                alldep = [],
                allusers = [];
            allcom.forEach(function(a) {
                if(a.deps && a.deps.length > 0 ) {
                    alldep = alldep.concat(a.deps)
                }
            })
            alldep.forEach(function(a) {
                if(a.users && a.users.length > 0 ) {
                    allusers = allusers.concat(a.users)
                }
            })
            $scope.allMembers = allusers

        }).catch(function error (error) {
            console.log(error)
        });
    }


    $scope.createGroup = function (groupName, groupIntro) {
        var memberList = [];

        angular.forEach($scope.allMembers, function (value, key) {
            if(value.checked && value.checked == true) {
                memberList.push(value.userid)
            } else if (value.userid == $rootScope.userId) {
                memberList.push(value.userid)
            }
        });

        mainServer.Group.createGroup(memberList.join(), groupName, groupIntro)
            .then(function success (data) {
                mainServer.User.getGroups($rootScope.userId)
                    .then(function success (data) {
                        $scope.grouplist = data.result
                        $scope.groupName = '';
                        $scope.groupIntro = '';
                        angular.forEach($scope.allMembers, function (value, key) {
                            value.checked = false;
                        });
                    })
                    .catch(function error (error){
                        console.log(error)
                    })
                $('#createGroupModal').modal('toggle')
            })
            .catch(function error (err){
                console.log(err)
            })
    }

    $scope.selectContact = function (userid) {
        $scope.$emit('contact', userid)
    }

    $scope.selectGroup = function (groupid) {
        $scope.$emit('group', groupid)
    }

    $scope.showList = function (outerIndex, innerIndex) {
      contactGroup[outerIndex + '_' + innerIndex] = !contactGroup[outerIndex + '_' + innerIndex]
    }

}]);



/*
 *
 *   聊天窗口控制器
 *
 */
chat.controller('chatroomController', ['$scope', '$rootScope', '$http', 'mainServer','mainDataServer', 'conversationServer', 'RongIMSDKServer', 'appconfig',
    function($scope, $rootScope, $http, mainServer, mainDataServer, conversationServer, RongIMSDKServer, appconfig){
    "use strict";
    $scope.targetId = null;

    $scope.userId = $rootScope.userId;

    $scope.msg_map = conversationServer.msg_map;

    $scope.messageList = conversationServer.conversationMessageListShow;

    $scope.sendButtonStatus = true

    $scope.sendMessage = function () {
        var msg = new RongIMLib.TextMessage({content: $scope.message, extra: "附加信息"});

        var conversationtype = RongIMLib.ConversationType.PRIVATE;
    		if($scope.targetInfo.groupid){
                conversationtype= RongIMLib.ConversationType.GROUP;
  		    }

        var targetId = $scope.targetId;

        if($scope.message && !$scope.message.match(/^[ ]*$/)) {
            RongIMSDKServer.sendMessage(conversationtype, targetId, msg)
            .then(function success(data) {
                $scope.message = "";
                data.senderUserName=window.LoginUser.username;
                data.portrait = window.LoginUser.portrait_uri;
                conversationServer.conversationMessageListShow.push(data);
                conversationServer.pushMsg(data);
            })
            .catch(function error(data) {
                console.log(data)
            })
            } else {
                if($scope.message.match(/^[ ]*$/)){
                    $scope.message = "";
                }
            }
    };
    //退出群组
    $scope.quitGroup = function (groupid, userid) {
        mainServer.Group.quitGroup(groupid, userid).then(function success (data) {
            mainServer.User.getGroups(userid)
                .then(function success (data) {
                    $scope.$emit('_grouplist', data.result);
                    $scope.targetInfo = {}
                    $('#quitGroupModal').modal('toggle')
                })
                .catch(function error (error){
                    console.log(error)
                })
        })
        .catch(function error (error) {
             console.log(error)
        })
    };
    //获取群组外其他人
    $scope.getOtherMember = function (groupid) {
        $scope.otherMembers = []

        mainServer.Department.getAllDepartment().then(function success (data) {
            var allcom = data.result,
                alldep = [],
                allusers = [],
                groupusers = [];
            angular.forEach(allcom, function(com, key){
                if(com.deps && com.deps.length > 0 ) {
                    alldep = alldep.concat(com.deps)
                }
            })
            angular.forEach(alldep, function(dep, key){
                if(dep.users && dep.users.length > 0 ) {
                    allusers = allusers.concat(dep.users)
                }
            });
            mainServer.Group.getGroupUserInfo(groupid).then(function success (data) {
                var diff = [];
                groupusers = data.result;
                angular.forEach(allusers, function (user, gkey) {
                    angular.forEach(groupusers, function (groupuser, ukey) {
                        if(groupuser.userid == user.userid) {
                            user.isExist = true
                        }
                    })
                });
                angular.forEach(allusers, function (user, key) {
                    if (user.isExist != true) {
                        diff.push(user)
                    }
                });

                $scope.otherMembers = diff;
            })
            .catch(function error (error) {
                console.log(error)
            })

        }).catch(function error (error) {
            console.log(error)
        });
    }
     //添加群成员
    $scope.addGroupMember = function (groupid, userid) {
        var memberList = [];

        angular.forEach($scope.otherMembers, function (value, key) {
            if(value.checked && value.checked == true) {
                memberList.push(value.userid)
            }
        });
        mainServer.Group.joinGroup(groupid, memberList.join(',')).then(function success (data) {
            $('#addGroupMemberModal').modal('toggle')
        })
        .catch(function error (error) {
            console.log(error)
        })
    };
    //获取群成员
    $scope.getAllGroupMember = function (groupid) {
        mainServer.Group.getGroupUserInfo(groupid).then(function success (data) {
            $scope.allGroupMember = data.result;
        })
        .catch(function error (error) {
            console.log(error)
        })
    }
    //删除群成员
    $scope.delGroupMember = function (groupid) {
        var memberList = [];

        angular.forEach($scope.allGroupMember, function (value, key) {
            if(value.checked && value.checked == true) {
                memberList.push(value.userid)
            }
        });
        mainServer.Group.quitGroup(groupid, memberList.join(',')).then(function success (data) {
            $('#delGroupMemberModal').modal('toggle')
        }).catch(function error (error) {
             console.log(error)
        })
    };
    //解散群
    $scope.destroyGroup = function (groupid, userid) {
        mainServer.Group.destroyGroup(groupid).then(function success (data) {
            mainServer.User.getGroups(userid)
                .then(function success (data) {
                    $scope.$emit('_grouplist', data.result);
                    $scope.targetInfo = {}
                    $('#destroyGroupModal').modal('toggle')
                })
                .catch(function error (error){
                    console.log(error)
                })
        })
    }

    $scope.$on('msg_in',function(e,data){
        mainServer.User.getUserInfo(data.senderUserId)
        .then(function success(result){
            data.senderUserName = result.result.username;
            data.protrait = result.result.portrait_uri;
            $scope.messageList.push(data);
            conversationServer.pushMsg(data);
        })
    });



    // 和人联系
    $scope.$on('conversation', function (e, data) {
        $scope.sendButtonStatus = false;
        $scope.targetId = data.targetId;
    	if(data.type=='user'){
            if (data.targetId) {
                mainServer.User.getUserInfo(data.targetId)
                .then(function success (data) {
                    var targetId = data.result;
                    var targetType = RongIMLib.ConversationType.PRIVATE

                    var currentCon = new webimmodel.Conversation();
                    currentCon.targetId = targetId;
                    currentCon.targetType = targetType;
                    $scope.currentCoversation = currentCon;
                    $scope.mainData = mainDataServer;
                    $scope.targetInfo = data.result
                    $scope.targetInfo.type = 'user';
                    $scope.targetInfo.mapkey="u_"+data.result.userid
                    // 获取会话列表 需要开通付费**** 注释掉
                    /*
                     * RongIMSDKServer.getConversation(targetType,
                     * targetId).then(function(data) { if (!data) { var conv =
                     * mainDataServer.conversation.createConversation(targetType,
                     * targetId); mainDataServer.conversation.currentConversation =
                     * conv; $scope.currentConversation = conv; } else {
                     * mainDataServer.conversation.currentConversation =
                     * mainDataServer.conversation.getConversation(targetType,
                     * targetId); $scope.currentConversation =
                     * mainDataServer.conversation.currentConversation; }
                     * $scope.currentConversation.draftMsg =
                     * RongIMSDKServer.getDraft(targetType, targetId);
                     *  }, function() {
                     *
                     * });
                     */
                    // RongIMSDKServer.clearUnreadCount(targetType, targetId);

                    conversationServer.historyMessagesCache[targetType + "_" + targetId] = conversationServer.historyMessagesCache[targetType + "_" + targetId] || [];

                    $scope.conversationServer = conversationServer;
                   // updateTargetDetail();

                })
                .catch(function error (data) {
                    console.log(data)
                })
            }
    	} else {
            if (data.targetId) {
                mainServer.Group.getGroupInfo(data.targetId)
                    .then(function success (data) {
                        var targetId = data.result.groupid;
                        var targetType = RongIMLib.ConversationType.GROUP
                        var currentCon = new webimmodel.Conversation();
                        currentCon.targetId = targetId;
                        currentCon.targetType = targetType;
                        $scope.currentCoversation = currentCon;
                        $scope.mainData = mainDataServer;
                        conversationServer.historyMessagesCache[targetType + "_" + targetId] = conversationServer.historyMessagesCache[targetType + "_" + targetId] || [];
                        $scope.conversationServer = conversationServer;
                        $scope.targetInfo = data.result;
                        $scope.targetInfo.type = 'group';
                        $scope.targetInfo.mapkey="u_"+data.result.groupid;
                        //console.log($scope.targetInfo)
                    });
            }
        }

    });


}])



/*
 * 公共方法
 * model 模型
 * util 公共方法
 *
 */

function model () {

    var Conversation = function () {
        this.title = '';
        this.targetId = '';
        this.targetType = null;
        this.lastTime = null;
        this.lastMsg = '';
        this.unReadNum = null;
        this.draftMsg = '';
        this.firstchar = '';
        this.imgSrc = '';
        this.pinyin = '';
        this.everychar = '';
        this.mentionedInfo = null;
        this.atStr = '';
    };

    Conversation.prototype.setpinyin = function (item) {
        "use strict";
        this.pinyin = item.pinyin;
        this.everychar = item.everychar
    },

    Conversation.prototype.convertToWebIM = function (item, operatorid) {
        "use strict";
        var lasttime;
        if(item.latestMessage && item.senTime) {
            lasttime = new Date(item.setTime);
        }

        var msgContent = ""
        if(item.latestMessage) {
            msgContent = Message.messageToNotification(item.latestMessage, operatorid, false)
        }
        return new Conversation({
            title: item.conversationTitle || "",
            targetId: item.targetId || "",
            targetType: item.conversationType || "",
            lastTime: lasttime || new Date(),
            lastMsg: msgContent || "",
            unReadNum: item.unreadMessageCount,
            draftMsg: item.draft || ""
        })
    }

    var MessageDirection = {
        SEND: 1,
        RECEIVE: 2
    }

    var ReceivedStatus = {
        READ: 0x1,
        LISTENED: 0x2,
        DOWNLOADED: 0x4
    }
    var SentStatus = {
        /**
		 * 发送中。
		 */
        SENDING: 10,
        /**
		 * 发送失败。
		 */
            FAILED: 20,
        /**
		 * 已发送。
		 */
            SENT: 30,
        /**
		 * 对方已接收。
		 */
            RECEIVED: 40,
        /**
		 * 对方已读。
		 */
            READ: 50,
        /**
		 * 对方已销毁。
		 */
            DESTROYED: 60,
    }
    var PanelType = {
        Message : 1,
        InformationNotification : 2,
        System : 103,
        Time : 104,
        getHistory : 105,
        getMore : 106,
        Other : 0
    }
    var AtTarget = {
        All: 1,
        Part: 2
    }
    var MessageType = {
        DiscussionNotificationMessage: "DiscussionNotificationMessage",
        TextMessage: "TextMessage",
        ImageMessage: "ImageMessage",
        VoiceMessage: "VoiceMessage",
        RichContentMessage: "RichContentMessage",
        HandshakeMessage: "HandshakeMessage",
        HandShakeResponseMessage: "HandShakeResponseMessage",
        UnknownMessage: "UnknownMessage",
        SuspendMessage: "SuspendMessage",
        LocationMessage: "LocationMessage",
        InformationNotificationMessage: "InformationNotificationMessage",
        ContactNotificationMessage: "ContactNotificationMessage",
        ProfileNotificationMessage: "ProfileNotificationMessage",
        CommandNotificationMessage: "CommandNotificationMessage",
        ReadReceiptMessage: "ReadReceiptMessage",
        TypingStatusMessage: "TypingStatusMessage",
        FileMessage: "FileMessage",
        GroupNotificationMessage: "GroupNotificationMessage",
        RecallCommandMessage: "RecallCommandMessage",
        InviteMessage: "InviteMessage",
        HungupMessage: "HungupMessage",
        ReadReceiptRequestMessage: "ReadReceiptRequestMessage",
        ReadReceiptResponseMessage: "ReadReceiptResponseMessage",
        SyncReadStatusMessage: "SyncReadStatusMessage"
    }
    var conversationType = {
        Private: 1,
        Discussion: 2,
        Group: 3,
        ChartRoom: 4,
        CustomerService: 5,
        System: 6,
        AppPublicService: 7,
        PublicService: 8
    }
    var NoticePanelType = {
        ApplyFriend : 1,
        AgreedFriend : 2,
        WarningNotice : 101,
        System : 102
    }
    return  {
        Conversation: Conversation,
        MessageDirection: MessageDirection,
        ReceivedStatus: ReceivedStatus,
        SentStatus: SentStatus,
        PanelType: PanelType,
        AtTarget: AtTarget,
        MessageType: MessageType,
        conversationType: conversationType,
        NoticePanelType: NoticePanelType
    }
}

function util() {
    "use strict";
    var CookieHelper = {};

    CookieHelper.setCookie = function(name, value, exires) {
        if (exires) {
            var date = new Date();
            date.setDate(date.getDate() + exires)
            document.cookie = name + "=" + encodeURI(value) + ";expires=" + date.toUTCString();
        } else {
            document.cookie = name + "=" + encodeURI(value) + ";";
        }
    };

    CookieHelper.getCookie = function(name) {
        var start = document.cookie.indexOf(name + "=");
        if (start != -1) {
            var end = document.cookie.indexOf(";", start);
            if (end == -1) {
                end = document.cookie.length;
            }
            return decodeURI(document.cookie.substring(start + name.length + 1, end));
        } else {
            return ""
        }
    };

    CookieHelper.removeCookie = function(name) {
        var exp = new Date();
        exp.setTime(exp.getTime() - 1);
        var cval= CookieHelper.getCookie(name);
        if(cval!=null)
            document.cookie= name + "="+cval+";expires="+exp.toGMTString();
    };

    return {
        CookieHelper: CookieHelper
    }
};
